package com.dhnsoft.数据结构与算法.栈与队列.栈;


import java.util.Scanner;

/**
 * ClassName: ArrayStackDemo
 * Package: com.dhnsoft.数据结构与算法.栈与队列.栈
 * Description:
 *
 * @Author dhn
 * @Create 2024/3/22 10:56
 * @Version 1.0
 */
public class ArrayStackDemo {
    public static void main(String[] args) {
        ArrayStack stack = new ArrayStack(3);
        char key = ' ';//接收用户输入
        Scanner scanner = new Scanner(System.in);
        boolean loop = true;
        //输出一个菜单
        while (loop){
            System.out.println("s(show): 显示队列");
            System.out.println("e(exit): 退出程序");
            System.out.println("a(push): 添加数据到队列");
            System.out.println("g(pop): 从队列取出数据");
            key = scanner.next().charAt(0);//接收一个字符
            switch (key){
                case 's':
                    try {
                        stack.showStack();
                    }
                    catch (Exception e){
                        System.out.println(e);
                    }
                    break;
                case 'a':
                    try {
                        System.out.println("输出一个数");
                        int value = scanner.nextInt();
                        stack.push(value);
                    }
                    catch (Exception e){
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'g':
                    try {
                        int res = stack.pop();
                        System.out.printf("取出得数据是%d\n",res);
                        break;
                    }catch (Exception e){
                        System.out.println(e.getMessage());
                    }
                case 'e':
                    scanner.close();
                    loop = false;
                    break;
                default:
                    break;
            }
            System.out.println("程序退出");
        }
    }
}

//定义一个ArrayStack表示栈
class ArrayStack{
    private int maxSize;

    private int[] stack;

    private int top = -1;

    public ArrayStack(int maxSize){
        this.maxSize = maxSize;
        stack = new int[maxSize];
    }

    //判断栈是否为空
    public boolean isEmpty(){
        return top==-1;
    }

    //判断栈是否满
    public boolean isFull(){
        return top == maxSize-1;
    }


    public int pop(){
        if(isEmpty()){
            throw new RuntimeException("栈为空");
        }
        int temp = stack[top];
        top--;
        return temp;
    }

    public void push(int n){
        if(isFull()){
            System.out.println("栈满了");
            return;
        }
        stack[++top] = n;
    }

    public void showStack(){
        if(isEmpty()){
            throw new RuntimeException("栈为空");
        }
        for (int i=maxSize-1;i>=0;i--){
            System.out.printf("stack[%d]=%d\n",i,stack[i]);
        }
    }

}